package com.bxd.baodan.widget;

import java.io.File;
import java.io.IOException;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;

public class MediaManager {

	private static MediaPlayer mPlayer;

	private static boolean isPause;

	@SuppressWarnings("resource")
	public static void playSound(String filePathString, String url,
			Context context, OnCompletionListener onCompletionListener) {
		// TODO Auto-generated method stub
		if (mPlayer == null) {
			mPlayer = new MediaPlayer();
			// 保险起见，设置报错监听
			mPlayer.setOnErrorListener(new OnErrorListener() {

				@Override
				public boolean onError(MediaPlayer mp, int what, int extra) {
					// TODO Auto-generated method stub
					mPlayer.reset();
					return false;
				}
			});
		} else {
			mPlayer.reset();// 就回复
		}

		try {
			mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
			mPlayer.setOnCompletionListener(onCompletionListener);
			// File file = new File(filePathString);
			// FileInputStream fis = new FileInputStream(file);
			// mPlayer.setDataSource(fis.getFD());
			mPlayer.setDataSource(filePathString);
			mPlayer.prepare();
			mPlayer.start();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 判断文件是否存在
	 * 
	 * @return
	 */
	public static boolean fileIsExists(String path) {
		try {
			File f = new File(path);
			if (!f.exists()) {
				return false;
			}

		} catch (Exception e) {
			// TODO: handle exception
			return false;
		}
		return true;
	}

	// 停止函数
	public static void pause() {
		if (mPlayer != null && mPlayer.isPlaying()) {
			mPlayer.pause();
			isPause = true;
		}
	}

	// 继续
	public static void resume() {
		if (mPlayer != null && isPause) {
			mPlayer.start();
			isPause = false;
		}
	}

	public static void release() {
		if (mPlayer != null) {
			mPlayer.stop();
			mPlayer.release();
			mPlayer = null;
		}
	}
}
